/**
 * @FunListMap.as
 *
 * @author sodaChen mail:asframe@qq.com
 * @version 1.0
 * <br>Copyright (C), 2013 asFrame.com
 * <br>This program is protected by copyright laws.
 * <br>Program Name:ASFrame
 * <br>Date:2016-11-8
 */
package com.asframe.fun
{
	import com.asframe.collections.maps.HashMap;
	import com.asframe.pool.IObjectPool;
	import com.asframe.pool.ObjectPool;
	import com.asframe.utils.VectorUtils;

	/**
	 * 函数对象以列表和集合的方式进行存放
	 * @author sodaChen
	 * Date:2016-11-8
	 */
	public class FunListMap
	{
		/** 统一使用的对象池 **/
		public static const pool:IObjectPool = new ObjectPool(FunListData,100,true);

		public var length			:int;
		/** 是否为执行一次就删除的类型 **/
		public var isOnce			:Boolean;
		private var funList		:Vector.<Function>;
		private var funMap			:HashMap;

		public function FunListMap(isOnce:Boolean = false)
		{
			this.isOnce = isOnce;
			funList = new Vector.<Function>();
			funMap = new HashMap();
		}
		/**
		 * 删除
		 * @param fun
		 * @param args
		 *
		 */
		public function addFun(fun:Function,args:Array = null,theThis:Object = null):void
		{
			if(funMap.hasKey(fun))
				return ;
			var funData:FunListData = pool.borrowObject();
			funData.fun = fun;
			funData.args = args;
			funData.theThis = theThis;
			funList.push(fun);
			funMap.put(fun,funData);
			length = funList.length;
		}
		public function removeFun(fun:Function):void
		{
			VectorUtils.removeItem(funList,fun);
			var funData:FunListData = funMap.remove(fun);
			length = funList.length;
			if(funData)
				pool.returnObject(funData);
		}
		/**
		 * 执行 函数
		 */
		public function executeFun():void
		{
			var funData:FunListData = null;
			var fun:Function = null;
			for (var i:int = 0; i < funList.length; i++)
			{
				funData = funMap.get(funList[i]);
				funList[i].apply(funData.theThis,funData.args);
				if(isOnce)
				{
					pool.returnObject(funData);
				}
			}
			if(isOnce)
			{
				funList.length = 0;
				funMap.clear();
			}
		}
	}
}
